<template>
  <template v-for="tag in fakeValue" :key="tag">
    <a-tooltip v-if="tag.length > 5" :title="tag">
      <a-tag
        v-bind="$attrs"
        :color="color"
        :closable="!disabled"
        @close="
          () => {
            let index = fakeValue.indexOf(tag)
            if (index !== -1) {
              fakeValue.splice(index, 1)
            }
          }
        "
      >
        {{ `${tag.slice(0, 5)}...` }}
      </a-tag>
    </a-tooltip>
    <a-tag
      v-else
      :color="color"
      :closable="!disabled"
      @close="
        () => {
          let index = fakeValue.indexOf(tag)
          if (index !== -1) {
            fakeValue.splice(index, 1)
          }
        }
      "
    >
      {{ tag }}
    </a-tag>
  </template>
  <a-input
    v-if="inputVisible"
    ref="inputRef"
    v-model:value="inputValue"
    type="text"
    size="small"
    :style="{ width: '78px' }"
    @blur="handleInputConfirm"
    @keyup.enter="handleInputConfirm"
  />
  <template v-else>
    <a-tag
      v-if="!disabled && (max == null || max > fakeValue.length)"
      style="background: #fff; border-style: dashed; cursor: pointer"
      @click="
        () => {
          inputVisible = true
          $nextTick(() => {
            $refs.inputRef.focus()
          })
        }
      "
    >
      <s-icon type="plus-outlined"></s-icon>
      添加
    </a-tag>
  </template>
</template>
<script>
export default {
  // 继承
  name: 'STag',
  props: {
    modelValue: {
      required: false
    },
    color: {
      required: false,
      type: String
    },
    max: {
      required: false,
      type: Number
    },
    disabled: {
      required: false,
      type: Boolean,
      default: false
    }
  },
  emits: ['change', 'update:modelValue'],
  data() {
    return {
      fakeValue: this.initValue(),
      inputVisible: false,
      inputValue: ''
    }
  },
  watch: {
    modelValue(val) {
      this.fakeValue = this.initValue()
    }
  },
  methods: {
    initValue() {
      let array = []
      if (this.modelValue) {
        array = this.modelValue.split(',')
      }
      return array
    },
    handleInputConfirm() {
      if (this.inputValue && this.fakeValue.indexOf(this.inputValue) === -1) {
        this.fakeValue.push(this.inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
      this.changeValue()
    },
    changeValue() {
      let value = ''
      this.fakeValue.forEach((item) => {
        if (value == '') {
          value = item
        } else {
          value = value + ',' + item
        }
      })

      this.$emit('update:modelValue', value)
      this.$emit('change', value)
    }
  }
}
</script>
